package com.study.mybatis.datasource;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yuantongqin
 * 2021/7/31
 **/
public class UnPoolDatasource {

    private final static List<Connection> connectionPool = new ArrayList<>();
    private String driver;
    private String url;
    private String username;
    private String password;

    public UnPoolDatasource(String driver, String url, String username, String password) {
        this.driver = driver;
        this.url = url;
        this.username = username;
        this.password = password;
    }

    public Connection doGetConnection() {
        if (connectionPool != null && connectionPool.size() > 0) {
            return connectionPool.get(0);
        }
        Connection connection = null;
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        if (connection != null) {
            connectionPool.add(connection);
        }
        return connection;
    }


}
